<template>
  <div class="multi-image-upload">
    <div class="image-list">
      <div 
        v-for="(item, index) in imageList" 
        :key="index" 
        class="image-item"
      >
        <div class="image-wrapper">
          <el-image
            :src="item.url"
            fit="cover"
            class="uploaded-image"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
          <!-- 图片操作按钮 -->
          <div class="image-actions">
            <span class="image-actions-span">
              <i class="el-icon-zoom-in" @click="handlePictureCardPreview(item)"></i>
              <i class="el-icon-delete" @click="removeImage(index)"></i>
            </span>
          </div>
        </div>
        <div class="image-name">
          <el-input
            v-model="item.name"
            placeholder="请输入图片名称"
            size="mini"
            @blur="updateImageName(index, item.name)"
          />
        </div>
      </div>
      
      <!-- 上传按钮 -->
      <div v-if="imageList.length < limit" class="upload-item">
        <el-upload
          :action="uploadImgUrl"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :before-upload="handleBeforeUpload"
          :on-error="handleUploadError"
          :on-progress="handleUploadProgress"
          accept=".jpg,.jpeg,.png,.gif"
          class="image-uploader"
        >
          <div class="upload-placeholder" v-if="!uploading">
            <i class="el-icon-plus"></i>
            <div class="upload-text">上传图片</div>
          </div>
          <!-- 上传进度 -->
          <div class="upload-progress" v-else>
            <el-progress 
              type="circle" 
              :percentage="uploadPercentage" 
              :width="60"
              :show-text="false"
            ></el-progress>
            <div class="progress-text">{{ uploadPercentage }}%</div>
          </div>
        </el-upload>
      </div>
    </div>
    
    <!-- 图片预览对话框 -->
    <el-dialog
      :visible.sync="dialogVisible"
      title="预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { listByIds } from "@/api/system/oss";

export default {
  name: "MultiImageUpload",
  props: {
    // mainImages: ossId字符串，逗号分隔
    mainImages: {
      type: String,
      default: ""
    },
    // mainDesc: 图片名称字符串，逗号分隔
    mainDesc: {
      type: String,
      default: ""
    },
    limit: {
      type: Number,
      default: 9
    },
    fileSize: {
      type: Number,
      default: 5
    },
    // 新增：是否返回URL而不是ossId
    returnUrl: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      imageList: [],
      uploading: false,
      uploadPercentage: 0,
      dialogVisible: false,
      dialogImageUrl: "",
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/system/oss/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      }
    };
  },
  watch: {
    mainImages: {
      handler() {
        this.loadImages();
      },
      immediate: true
    },
    mainDesc: {
      handler() {
        this.loadImages();
      },
      immediate: true
    }
  },
  methods: {
    // 加载图片数据
    async loadImages() {
      if (!this.mainImages) {
        this.imageList = [];
        return;
      }
      
      try {
        const items = this.mainImages.split(',').filter(item => item.trim());
        const names = this.mainDesc ? this.mainDesc.split(',') : [];
        
        if (items.length === 0) {
          this.imageList = [];
          return;
        }
        
        // 检查第一个项目是否为 URL
        const firstItem = items[0].trim();
        if (firstItem.startsWith('http://') || firstItem.startsWith('https://')) {
          // 如果是 URL，直接构建图片列表
          this.imageList = items.map((url, index) => ({
            ossId: `temp_${index}`, // 临时 ossId
            url: url.trim(),
            name: names[index] || `图片${index + 1}`,
            fileName: url.split('/').pop() || `image_${index + 1}`
          }));
        } else {
          // 如果是 ossId，通过接口获取图片信息
          const response = await listByIds(items.join(','));
          if (response.code === 200) {
            this.imageList = response.data.map((item, index) => ({
              ossId: item.ossId,
              url: item.url,
              name: names[index] || `图片${index + 1}`,
              fileName: item.fileName
            }));
          }
        }
      } catch (error) {
        console.error('加载图片失败:', error);
        this.imageList = [];
      }
    },
    
    // 上传前验证
    handleBeforeUpload(file) {
      const isJPG = /\.(jpg|jpeg|png|gif)$/i.test(file.name);
      const isLt5M = file.size / 1024 / 1024 < this.fileSize;
      
      if (!isJPG) {
        this.$modal.msgError('上传图片只能是 JPG/JPEG/PNG/GIF 格式!');
        return false;
      }
      if (!isLt5M) {
        this.$modal.msgError(`上传图片大小不能超过 ${this.fileSize}MB!`);
        return false;
      }
      
      // 开始上传，显示进度
      this.uploading = true;
      this.uploadPercentage = 0;
      return true;
    },
    
    // 上传进度
    handleUploadProgress(event) {
      this.uploadPercentage = Math.round(event.percent);
    },
    
    // 上传成功
    handleUploadSuccess(res) {
      // 重置上传状态
      this.uploading = false;
      this.uploadPercentage = 0;
      
      if (res.code === 200) {
        const newImage = {
          ossId: res.data.ossId,
          url: res.data.url,
          name: `图片${this.imageList.length + 1}`,
          fileName: res.data.fileName
        };
        this.imageList.push(newImage);
        this.emitChange();
        this.$modal.msgSuccess('上传成功');
      } else {
        this.$modal.msgError('上传失败');
      }
    },
    
    // 上传失败
    handleUploadError() {
      // 重置上传状态
      this.uploading = false;
      this.uploadPercentage = 0;
      this.$modal.msgError('上传失败');
    },
    
    // 预览图片
    handlePictureCardPreview(item) {
      this.dialogImageUrl = item.url;
      this.dialogVisible = true;
    },
    
    // 更新图片名称
    updateImageName(index, name) {
      if (name.trim()) {
        this.imageList[index].name = name.trim();
        this.emitChange();
      }
    },
    
    // 删除图片
    removeImage(index) {
      this.$confirm('确定要删除这张图片吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.imageList.splice(index, 1);
        this.emitChange();
        this.$modal.msgSuccess('删除成功');
      });
    },
    
    // 触发change事件
    emitChange() {
      let mainImagesValue;
        if (this.returnUrl) {
          // 返回URL格式
          mainImagesValue = this.imageList.map(item => item.url).join(',');
        } else {
          // 返回ossId格式（原有逻辑）
          mainImagesValue = this.imageList.map(item => item.ossId).join(',');
        }
        
        const names = this.imageList.map(item => item.name).join(',');
        
        this.$emit('update:mainImages', mainImagesValue);
        this.$emit('update:mainDesc', names);
        this.$emit('change', {
          mainImages: mainImagesValue,
          mainDesc: names,
          imageList: this.imageList
        });
    }
  }
};
</script>

<style scoped>
.multi-image-upload {
  width: 100%;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item, .upload-item {
  width: 120px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.image-wrapper {
  position: relative;
  width: 100%;
  height: 120px;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

/* 仿照ImageUpload的图片操作样式 */
.image-actions {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  cursor: default;
  text-align: center;
  color: #fff;
  opacity: 0;
  font-size: 20px;
  background-color: rgba(0, 0, 0, 0.5);
  transition: opacity 0.3s;
}

.image-wrapper:hover .image-actions {
  opacity: 1;
}

.image-actions-span {
  display: inline-block;
  margin-top: 40%;
  transform: translateY(-50%);
}

.image-actions i {
  color: #fff;
  margin: 0 6px;
  cursor: pointer;
  font-size: 18px;
}

.image-actions i:hover {
  color: #409eff;
}

.image-name {
  padding: 5px;
}

.upload-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 160px;
  cursor: pointer;
  border-style: dashed;
  transition: border-color 0.3s;
}

.upload-item:hover {
  border-color: #409eff;
}

.image-uploader {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  color: #8c939d;
  text-align: center;
}

.upload-placeholder i {
  font-size: 28px;
  margin-bottom: 8px;
  line-height: 1;
}

.upload-text {
  font-size: 12px;
  line-height: 1;
}

/* 上传进度样式 */
.upload-progress {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.progress-text {
  margin-top: 8px;
  font-size: 12px;
  color: #606266;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>